<template>
  <div class="app-container">
    <!-- 数据查询区：表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="口味名称" prop="tasteName">
        <el-input
          v-model="queryParams.tasteName"
          placeholder="请输入口味名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据操作区：按钮 -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Delete" @click="handleDeleteBatch" :disabled="!multiple">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据展示区：表格 -->
    <el-table v-loading="loading" :data="tastes" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" width="250" prop="tasteId" />
      <el-table-column label="口味名称" align="center" width="250" prop="tasteName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 数据展示区：分页加载 -->
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 数据编辑区：新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="口味名称" prop="tasteName">
          <el-input v-model="form.tasteName" placeholder="请输入口味名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
          <el-button @click="resetForm(formRef)" v-show="form.tasteName === undefined">重 置</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
/** ------------------全局导入区-------------------- */
import { ref, reactive, toRef, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type{ QueryParams, TasteDTO, RuleForm } from "@/views/dish/taste/types";
import { listAllTaste, listTaste, listTasteByPage, getTasteById, getTasteByName, addTaste, updateTaste, deleteTaste, deleteTasteBatch } from '@/api/taste';

onMounted(() => {
// 挂载后加载数据
getList()
})

/** ------------------数据查询区——表单-------------------- */
// 表单实例
const queryRef = ref<FormInstance>()

// 查询
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  tasteName: ''
})
const queryParams = toRef(query)
// 数据查询区--> 查询按钮
function handleQuery() {
queryParams.value.pageNum = 1
getList()
ElMessage.success(JSON.stringify(queryParams.value))
}
// 数据查询区--> 重置按钮
const resetQuery = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.resetFields()
getList()
}

/** ------------------数据展示区——表格-------------------- */

// 数据列表
const loading = ref<boolean>(false)  // table数据加载遮罩
const total = ref<number>(0) // table数据总数
const isEditMode = ref(false)

const tasteData = reactive<TasteDTO[]>([]) // table数据
const tastes = toRef(tasteData)

// 数据展示区--> 数据加载
const getList = async () => {
  loading.value = true
  /** 调用后端分页查询接口 */
  listTasteByPage(queryParams.value).then(response => {
    tastes.value = response.data.list
    total.value = response.data.total
    loading.value = false
  })
}

/** ------------------数据展示区：数据选择-------------------- */

const ids = ref<number[]>([]) // 表单勾选的id
const single = ref<boolean>(false) // 勾选1个
const multiple = ref<boolean>(false) // 勾选多个

// 数据展示区--> 勾选数据
function handleSelectionChange(selection: TasteDTO[]) {
ids.value = selection.map((item:TasteDTO) => item.tasteId)
single.value = selection.length == 1
multiple.value = selection.length >= 1 

}

/** ------------------数据展示区：分页加载-------------------- */
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val:number) {
queryParams.value.pageSize = val
getList()
}

//分页--> 修改当前页
function handleCurrentChange(val:number) {
queryParams.value.pageNum = val
getList()
}

/** ------------------数据编辑区——对话框+表单-------------------- */
// 表单数据
const formRef = ref<FormInstance>()

const formData = reactive<RuleForm>({
  tasteName: ''
})
const form  = toRef(formData)
const rules = reactive<FormRules<RuleForm>>({ // 表单验证规则
  tasteName: [
  { required: true, message: '口味名称不能为空', trigger: 'blur' },
]
})

// 对话框数据
const title = ref('') // 对话框标题
const open = ref(false) //对话框打开

// 数据编辑区-->提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

await formEl.validate((valid, fields) => {
    if (valid) {
      /** 调用后端新增接口 */
        addTaste(form.value).then((response) => {
          ElMessage({type: 'success',message: '新增数据成功'})
        })
      
      getList()
      open.value = false
      ElMessage.success(JSON.stringify(form.value))
    } else {
      console.log('表单验证未通过', fields) // 前台会自动提示errors
    }
})
}

// 数据编辑区-->重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// 数据编辑区-->取消按钮
function cancel(){
initForm()
open.value = false
}

/** ------------------数据操作区——按钮-------------------- */
// 清空或赋值表单数据
const initForm = () => {
// formRef.value?.resetFields() 
form.value = {
  tasteName: ''
}
}

// 数据操作区--> 新增按钮
function handleAdd() {
  isEditMode.value = false //标记为新增模式
initForm()
title.value = '新增口味'
open.value = true
}

// 数据操作区--> 删除按钮
async function handleDelete(row: any) {
  const id = row.tasteId
  ElMessageBox.confirm('是否删除编号为' + id + '的数据?','警告')
    .then(() =>{
      return deleteTaste(id)
    })
    .then(() => {
        getList()
        ElMessage({type: 'success',message: '删除成功'})
    })
    .catch(() => {})    
}

// 数据操作区--> 批量删除
async function handleDeleteBatch() {
  const tasteIds = ids.value
  ElMessageBox.confirm('是否批量删除编号为' + tasteIds + '的数据?','警告')
    .then(() => {
      return deleteTasteBatch(tasteIds)
    })
    .then(() => {
        getList()
        ElMessage({type: 'success',message: '批量删除成功',})
    })
    .catch(() => {})  
}

</script>